const app = getApp()
const { showToast, showLoading, hideLoading, chooseAddress } = require('./tips')

const ORDER_STATUS = {
  PENDING: {
    value: 'pending',
    desc: '待付款'
  },
  PROCESSING: {
    value: 'processing',
    desc: '已付款'
  },
  COMPLETED: {
    value: 'completed',
    desc: '已完成'
  },
  CANCELLED: {
    value: 'cancelled',
    desc: '已取消'
  }
}

// 生成订单号
function generateOrderNo() {
  const now = new Date()
  const year = now.getFullYear().toString().slice(2)
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const day = now.getDate().toString().padStart(2, '0')
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  const seconds = now.getSeconds().toString().padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `ON${year}${month}${day}${hours}${minutes}${seconds}${random}`
}

// 更新商品库存
async function updateProductStock(products) {
  const db = wx.cloud.database()
  const _ = db.command

  for (const product of products) {
    const { id, quantity, specs } = product
    
    try {
      // 获取商品信息
      const { data: productData } = await db.collection('products').doc(id).get()
      
      if (productData.specCombos && specs) {
        // 找到匹配的规格组合
        const comboIndex = productData.specCombos.findIndex(combo => 
          Object.entries(combo.specs).every(([key, value]) => specs[key] === value)
        )
        
        if (comboIndex !== -1) {
          // 更新指定规格组合的库存
          const updatePath = `specCombos.${comboIndex}.stock`
          await db.collection('products').doc(id).update({
            data: {
              [updatePath]: _.inc(-quantity)
            }
          })
        } else {
          console.error('未找到匹配的规格组合:', specs)
        }
      }
    } catch (error) {
      console.error('更新商品库存失败:', error)
      throw error
    }
  }
}

// 创建并支付订单
async function createAndPayOrder(orderData) {
  const db = wx.cloud.database()
  
  try {
    // 创建订单前检查库存
    for (const product of orderData.products) {
      const { data: productData } = await db.collection('products').doc(product.id).get()
      
      if (productData.specCombos && product.specs) {
        // 找到匹配的规格组合
        const matchedCombo = productData.specCombos.find(combo => 
          Object.entries(combo.specs).every(([key, value]) => product.specs[key] === value)
        )
        
        if (!matchedCombo) {
          throw new Error(`商品 ${product.name} 的规格组合不存在`)
        }
        
        if (matchedCombo.stock < product.quantity) {
          throw new Error(`商品 ${product.name} 库存不足`)
        }
      }
    }

    // 创建订单
    showLoading('正在创建订单...')
    const orderNo = generateOrderNo()
    const now = Date.now()
    
    // 创建订单
    const { _id: orderId } = await db.collection('orders').add({
      data: {
        orderNo,
        userId: app.globalData.openid,
        ...orderData,
        status: ORDER_STATUS.PENDING.value,
        statusDesc: ORDER_STATUS.PENDING.desc,
        payStatus: 'unpaid',
        orderStatus: 'created',
        deliveryStatus: 'undelivered',
        createTime: { $date: now },
        updateTime: { $date: now },
        timeline: [{
          status: 'created',
          statusDesc: '订单创建',
          time: { $date: now }
        }]
      }
    })

    try {
      // 调用支付
      const res = await wx.cloud.callFunction({
        name: 'pay',
        data: {
          orderId,
          totalFee: orderData.totalAmount * 100
        }
      })

      hideLoading()

      if (res.result && res.result.payment) {
        try {
          await wx.requestPayment({
            ...res.result.payment
          })
          
          // 支付成功，更新订单状态
          await db.collection('orders').doc(orderId).update({
            data: { 
              status: ORDER_STATUS.PROCESSING.value,
              statusDesc: ORDER_STATUS.PROCESSING.desc,
              payStatus: 'paid',
              updateTime: db.serverDate(),
              timeline: db.command.push({
                status: ORDER_STATUS.PROCESSING.value,
                statusDesc: '支付完成',
                time: db.serverDate()
              })
            }
          })

          // 更新商品库存
          await updateProductStock(orderData.products)
          
          showToast('支付成功', 'success')
        } catch (payError) {
          console.log('支付失败或取消：', payError)
          // 支付失败或取消，保持订单状态为待付款
          await db.collection('orders').doc(orderId).update({
            data: {
              status: ORDER_STATUS.PENDING.value,  // 待付款
              statusDesc: ORDER_STATUS.PENDING.desc,
              payStatus: 'unpaid',
              updateTime: db.serverDate()
            }
          })
          
          showToast('支付失败或已取消', 'none')
        }
      } else {
        throw new Error('支付请求失败')
      }
    } catch (error) {
      console.error('支付过程出错：', error)
      showToast('支付过程出错', 'none')
    }
    
    // 无论支付结果如何，都返回订单ID
    return { orderId }
  } catch (error) {
    hideLoading()
    console.error('订单创建失败：', error)
    throw error
  }
}

module.exports = {
  createAndPayOrder,
  ORDER_STATUS
} 